package com.cqjtu.tto.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqjtu.tto.dao.mapper.DepartmentMapper;
import com.cqjtu.tto.dao.mapper.RoleMapper;
import com.cqjtu.tto.dao.mapper.SysUserMapper;
import com.cqjtu.tto.dao.mapper.SysUserRoleMapper;
import com.cqjtu.tto.dao.pojo.Department;
import com.cqjtu.tto.dao.pojo.Role;
import com.cqjtu.tto.dao.pojo.SysUser;
import com.cqjtu.tto.dao.pojo.SysUserRole;
import com.cqjtu.tto.service.SysUserService;
import com.cqjtu.tto.vo.*;
import com.cqjtu.tto.vo.params.SysUserParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author：monkey-L
 * @description:
 * @date: 19:55 2021/12/11
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public Results sysUserUpdate(SysUserParam sysUserParam) {
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        sysUserWrapper.eq(SysUser::getUserName,sysUserParam.getUserName()).last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(sysUserWrapper);
        SysUser sysUser1 = new SysUser();
        BeanUtils.copyProperties(sysUserParam,sysUser1);
        sysUser1.setUserId(sysUser.getUserId());
        LambdaQueryWrapper<Department> departmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        departmentLambdaQueryWrapper.eq(Department::getDepartmentName,sysUserParam.getDepartmentName()).last("limit 1");
        Department department = departmentMapper.selectOne(departmentLambdaQueryWrapper);
        sysUser1.setDepartmentId(department.getDepartmentId());
        sysUser1.setUserDeleted(0);
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper1.eq(SysUser::getUserId,sysUser.getUserId());
        sysUserMapper.update(sysUser1,sysUserLambdaQueryWrapper1);
        List<String> roleName = sysUserParam.getRoleName();
        for (String s : roleName) {
            LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roleLambdaQueryWrapper.eq(Role::getRoleName,roleName).last("limit 1");
            Role role = roleMapper.selectOne(roleLambdaQueryWrapper);
            LambdaQueryWrapper<SysUserRole> sysUserRoleWrapper = new LambdaQueryWrapper<>();
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRoleWrapper.eq(SysUserRole::getUserId,sysUser.getUserId()).last("limit 1");
            SysUserRole sysUserRole1 = sysUserRoleMapper.selectOne(sysUserRoleWrapper);
            sysUserRole.setUserId(sysUser1.getUserId());
            sysUserRole.setUserRoleId(sysUserRole1.getUserRoleId());
            sysUserRole.setUserRoleDeleted(0);
            sysUserRole.setRoleId(role.getRoleId());
            LambdaQueryWrapper<SysUserRole> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysUserRoleMapper.update(sysUserRole,sysUserLambdaQueryWrapper);
        }
        return Results.success("更新成功！");
    }
    /*
     * 业务实现逻辑:
     *  1.查询是否有这个用户；
     *  2.如果不存在，则返回删除失败信息
     *  3.如果存在，则查询该用户的角色；
     *  4.如果不存在，则从数据库删除该用户
     *  5.如果存在，则删除用户-角色记录
     *  6.从数据库删除该用户，返回删除成功
     * @author monkey-L
     * @param SysUserRoleParam sysUserRoleParam
     * @return Results
     */
    @Override
    @Transactional
    public Results sysUserDelete(String userName) {
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        sysUserWrapper.eq(SysUser::getUserName,userName).last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(sysUserWrapper);
        if (sysUser == null) {
            return Results.fail(ErrorCode.USER_NOT_EXIST.getCode(),ErrorCode.USER_NOT_EXIST.getMsg());
        }
        LambdaQueryWrapper<SysUserRole> sysUserRoleWrapper = new LambdaQueryWrapper<>();
        sysUserRoleWrapper.eq(SysUserRole::getUserId,sysUser.getUserId());
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(sysUserRoleWrapper);
        for (SysUserRole sysUserRole : sysUserRoles) {
            LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserRoleId,sysUserRole.getUserRoleId());
            sysUserRoleMapper.delete(sysUserRoleLambdaQueryWrapper);
        }
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getUserId,sysUser.getUserId());
        sysUserMapper.delete(sysUserLambdaQueryWrapper);
        return Results.success("删除成功！");
    }

    @Override
    @Transactional
    public Results sysUserSelectOne(String userName) {
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        sysUserWrapper.eq(SysUser::getUserName,userName).last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(sysUserWrapper);
        if (sysUser == null) {
            return Results.fail(ErrorCode.USER_NOT_EXIST.getCode(),ErrorCode.USER_NOT_EXIST.getMsg());
        }
        LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
        departmentWrapper.eq(Department::getDepartmentId,sysUser.getDepartmentId()).last("limit 1");
        Department department = departmentMapper.selectOne(departmentWrapper);
        SysUserVo sysUserVo = new SysUserVo();
        System.out.println("=============");
        System.out.println(sysUser);
        System.out.println("=============");

        BeanUtils.copyProperties(sysUser,sysUserVo);
        sysUserVo.setDepartmentName(department.getDepartmentName());
        LambdaQueryWrapper<SysUserRole> sysUserRoleWrapper = new LambdaQueryWrapper<>();
        sysUserRoleWrapper.eq(SysUserRole::getUserId,sysUser.getUserId());
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(sysUserRoleWrapper);
        List<String> list = new ArrayList<>();
        for (SysUserRole sysUserRole : sysUserRoles) {
            LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.eq(Role::getRoleId,sysUserRole.getRoleId()).last("limit 1");
            Role role = roleMapper.selectOne(roleWrapper);
            list.add(role.getRoleName());
        }
        sysUserVo.setRoleName(list);
        return Results.success(sysUserVo);
    }

    @Override
    @Transactional
    public Results sysUserSelectList() {
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        List<SysUser> sysUsers = sysUserMapper.selectList(sysUserWrapper);
        ArrayList<SysUserVo> sysUserVos = new ArrayList<>();
        for (SysUser sysUser : sysUsers) {
            LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
            departmentWrapper.eq(Department::getDepartmentId,sysUser.getDepartmentId()).last("limit 1");
            Department department = departmentMapper.selectOne(departmentWrapper);
            SysUserVo sysUserVo = new SysUserVo();
            BeanUtils.copyProperties(sysUser,sysUserVo);
            sysUserVo.setDepartmentName(department.getDepartmentName());
            LambdaQueryWrapper<SysUserRole> sysUserRoleWrapper = new LambdaQueryWrapper<>();
            sysUserRoleWrapper.eq(SysUserRole::getUserId,sysUser.getUserId());
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(sysUserRoleWrapper);
            List<String> list = new ArrayList<>();
            for (SysUserRole sysUserRole : sysUserRoles) {
                LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
                roleWrapper.eq(Role::getRoleId,sysUserRole.getRoleId()).last("limit 1");
                Role role = roleMapper.selectOne(roleWrapper);
                list.add(role.getRoleName());
            }
            sysUserVo.setRoleName(list);
            sysUserVos.add(sysUserVo);
        }
        return Results.success(sysUserVos);
    }

    @Override
    @Transactional
    public void customerExport(HttpServletResponse response) {
        try {
            String fileName = URLEncoder.encode("客户信息.xlsx", "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            //设置类型，扩展名为.xls
            response.setContentType("application/vnd.ms-excel");
            ServletOutputStream out = response.getOutputStream();
            EasyExcel.write(out, CustomerDataExcel.class).sheet("sheet1").doWrite(getData());
            response.flushBuffer();
//            return Results.success("数据导出成功！");
        } catch (Exception e) {
            e.printStackTrace();
//            return Results.fail(1038,"数据导出失败！");
        }
    }

        @Override
        public void     sysUserExport(HttpServletResponse response) {
            try {
                String fileName = URLEncoder.encode("员工信息.xlsx", "UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                //设置类型，扩展名为.xls
                response.setContentType("application/vnd.ms-excel");
                ServletOutputStream out = response.getOutputStream();
                EasyExcel.write(out, SysUserDataExcel.class).sheet("sheet1").doWrite(getData1());
                response.flushBuffer();
    //            return Results.success("数据导出成功！");
            } catch (Exception e) {
                e.printStackTrace();
    //            return Results.fail(1038,"数据导出失败！");
            }
        }

    //创建方法返回list集合
    private List<CustomerDataExcel> getData() {
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        List<SysUser> sysUsers = sysUserMapper.selectList(sysUserWrapper);
        ArrayList<SysUserVo> sysUserVos = new ArrayList<>();
        for (SysUser sysUser : sysUsers) {
            LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
            departmentWrapper.eq(Department::getDepartmentId,sysUser.getDepartmentId()).last("limit 1");
            Department department = departmentMapper.selectOne(departmentWrapper);
            SysUserVo sysUserVo = new SysUserVo();
            BeanUtils.copyProperties(sysUser,sysUserVo);
            sysUserVo.setDepartmentName(department.getDepartmentName());
            LambdaQueryWrapper<SysUserRole> sysUserRoleWrapper = new LambdaQueryWrapper<>();
            sysUserRoleWrapper.eq(SysUserRole::getUserId,sysUser.getUserId());
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(sysUserRoleWrapper);
            List<String> list = new ArrayList<>();
            for (SysUserRole sysUserRole : sysUserRoles) {
                LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
                roleWrapper.eq(Role::getRoleId,sysUserRole.getRoleId()).last("limit 1");
                Role role = roleMapper.selectOne(roleWrapper);
                list.add(role.getRoleName());
            }
            sysUserVo.setRoleName(list);
            sysUserVos.add(sysUserVo);
        }
        List<CustomerDataExcel> list = new ArrayList<>();
        for (SysUserVo sysUserVo : sysUserVos) {
            if (sysUserVo.getDepartmentName().equals("顾客")) {
                CustomerDataExcel dataExcel = new CustomerDataExcel();
                dataExcel.setUserName(sysUserVo.getUserName());
                dataExcel.setUserTel(sysUserVo.getUserTel());
                dataExcel.setUserQq(sysUserVo.getUserQq());
                dataExcel.setUserEmail(sysUserVo.getUserEmail());
                dataExcel.setUserUnitFirst(sysUserVo.getUserUnitFirst());
                dataExcel.setUserUnitSecond(sysUserVo.getUserUnitSecond());
                dataExcel.setUserSex(sysUserVo.getUserSex());
                list.add(dataExcel);
            }
        }
        return list;
    }

    //创建方法返回list集合
    private List<SysUserDataExcel> getData1() {
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        List<SysUser> sysUsers = sysUserMapper.selectList(sysUserWrapper);
        ArrayList<SysUserVo> sysUserVos = new ArrayList<>();
        for (SysUser sysUser : sysUsers) {
            LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
            departmentWrapper.eq(Department::getDepartmentId,sysUser.getDepartmentId()).last("limit 1");
            Department department = departmentMapper.selectOne(departmentWrapper);
            SysUserVo sysUserVo = new SysUserVo();
            BeanUtils.copyProperties(sysUser,sysUserVo);
            sysUserVo.setDepartmentName(department.getDepartmentName());
            LambdaQueryWrapper<SysUserRole> sysUserRoleWrapper = new LambdaQueryWrapper<>();
            sysUserRoleWrapper.eq(SysUserRole::getUserId,sysUser.getUserId());
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(sysUserRoleWrapper);
            List<String> list = new ArrayList<>();
            for (SysUserRole sysUserRole : sysUserRoles) {
                LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
                roleWrapper.eq(Role::getRoleId,sysUserRole.getRoleId()).last("limit 1");
                Role role = roleMapper.selectOne(roleWrapper);
                list.add(role.getRoleName());
            }
            sysUserVo.setRoleName(list);
            sysUserVos.add(sysUserVo);
        }
        List<SysUserDataExcel> list = new ArrayList<>();
        for (SysUserVo sysUserVo : sysUserVos) {
            if (!sysUserVo.getDepartmentName().equals("顾客")) {
                SysUserDataExcel dataExcel = new SysUserDataExcel();
                dataExcel.setUserName(sysUserVo.getUserName());
                dataExcel.setUserTel(sysUserVo.getUserTel());
                dataExcel.setUserQq(sysUserVo.getUserQq());
                dataExcel.setUserEmail(sysUserVo.getUserEmail());
                dataExcel.setUserSex(sysUserVo.getUserSex());
                dataExcel.setDepartmentName(sysUserVo.getDepartmentName());
//                dataExcel.setRoleName(sysUserVo.getRoleName());
                list.add(dataExcel);
            }

        }
        return list;
    }

}
